<template>
	<div
		:class="[
			'app-editor-container',
			'app-radio-group',
			`app-radio-group-${name}`,
		]"
	>
		<a-radio-group
			@change="onChange"
			:value="value"
			:options="items"
			:disabled="disabled || readOnly"
		>
		</a-radio-group>
	</div>
</template>
<script setup lang="ts">
import { ICodeListItem, IEvent, typeOf } from '@/core';
import { onBeforeMount, ref, Ref } from 'vue';
import { radioGroupProps } from './radio-group';
import { handleEditorNavParams } from '@/hooks/use-editor';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(radioGroupProps);
const emit = defineEmits<EditorEmit>();
const { navContext, navViewParam } = handleEditorNavParams(props);
let items: Ref<any[]> = ref([]);

const onChange = ($event: any) => {
	const value = $event.target.value;
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	});
};

const formatCodeList = (items: Array<any>) => {
	let matching = false;
	let result: Array<any> = [];
	try {
		items.forEach((item: any) => {
			const type = typeOf(item.value);
			if (type != props.valueType) {
				matching = true;
				if (type === 'number') {
					item.value = item.value.toString();
				} else {
					if (type == 'null') {
						props.valueType == 'number' ? (item.value = 0) : (item.value = '');
					} else if (item.value.indexOf('.') == -1) {
						item.value = parseInt(item.value);
					} else {
						item.value = parseFloat(item.value);
					}
				}
			}
			result.push(item);
		});
		if (matching) {
			console.warn(
				App.ts(
					'common.generic.codelistcast',
					'代码表值类型和属性类型不匹配，自动强制转换'
				)
			);
		}
		return result;
	} catch (error) {
		console.warn(
			App.ts(
				'common.generic.codelistwarn',
				'代码表值类型和属性类型不匹配，自动强制转换异常，请修正代码表值类型和属性类型匹配'
			)
		);
		return [];
	}
};

onBeforeMount(() => {
	loadData();
});

const loadData = async () => {
	if (props.codeListTag && props.codeListType) {
		const codeListResult = await App.getAppCodeListHelper()
			.getCodeListItems(props.codeListTag, navContext, navViewParam)
			.then((codeListResult: any) => {
				if (codeListResult.ok) {
					const result = formatCodeList(codeListResult.data);
					result.forEach((item: ICodeListItem) => {
						items.value.push({ ...item, label: item.text });
					});
				}
			})
			.catch((error: any) => {
				console.error(App.ts('common.generic.codenotexist', '代码表不存在'));
			});
	}
};
</script>
